import type {ChatModel} from "@/interface/ChatModel";
import { useSocket } from "@/stores/Socket";
import { useLoginStore } from "@/stores/loginStore";
import { emitter } from "@/utils/Mitt"
import { onMounted, onUnmounted } from "vue";
import { notification } from "ant-design-vue";



export default function () {


    let socket = useSocket();
    let loginStore = useLoginStore();

    onMounted(() => {
        InitSocket();
    });

    emitter.on("connectWs", ()=> {
        InitSocket();
    });

    onUnmounted(()=> {
        if (loginStore.loginInfo.user && loginStore.loginInfo.user.user.id) {
            socket.send({ cmd: 199 , userId : loginStore.loginInfo.user.user.id } as ChatModel);
        }
        socket.destroy();
    });

    function InitSocket() {
        if (loginStore.loginInfo.user && loginStore.loginInfo.user.user.id) {
            let activeToken  = { msg: 'PING' , cmd : 205 } as ChatModel;
            let connectionKey   = { userId: loginStore.loginInfo.user.user.id , cmd : 200 } as ChatModel;
            socket.InitWS(import.meta.env.Ex_Socket,connectionKey,activeToken,received);
        }

    }

    function received(data : string) {
        let chat = JSON.parse(data) as ChatModel;
        if (chat.type == 3) {
            notification.success({
                message: `系统推送通知`,
                description: chat.msg,
                duration: 2
            });
        }else {
            emitter.emit("socketMsg",chat);
        }
    }


    return {}

}
